<script setup lang="tsx">
import { reactive, ref, unref } from 'vue'
import { deleteDataApi, selectPageApi, selectFormDetail } from '@/api/sysGenForm'
import { useTable } from '@/hooks/web/useTable'
import { useI18n } from '@/hooks/web/useI18n'
import { Table, TableColumn } from '@/components/Table'
import { Search } from '@/components/Search'
import { FormSchema } from '@/components/Form'
import { ContentWrap } from '@/components/ContentWrap'
import Write from './components/Write.vue'
import { Dialog } from '@/components/Dialog'
import { BaseButton } from '@/components/Button'
import { useSearch } from '@/hooks/web/useSearch'
import { useRouter } from 'vue-router'
import VFormRender from '@/components/variant-form3/form-render/index.vue'
const { push } = useRouter()
const { t } = useI18n()

const { searchRegister, searchMethods } = useSearch()
const { getFormData } = searchMethods
const id = ref<string>()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const formData = await getFormData()
    console.log('formData', formData)
    const res = await selectPageApi({
      formName: formData.formName,
      page: { size: unref(pageSize), current: unref(currentPage) }
    })
    return {
      list: res.result.records || [],
      total: res.result.total
    }
  },
  fetchDelApi: async () => {
    const res = await deleteDataApi({ id: id.value })
    return !!res
  }
})
const { dataList, loading, total, currentPage, pageSize } = tableState

const { getList, refresh, delList, getElTableExpose } = tableMethods

const tableColumns = reactive<TableColumn[]>([
  {
    field: 'index',
    label: t('userDemo.index'),
    type: 'index'
  },
  {
    field: 'formName',
    label: '表单名称'
  },
  {
    field: 'modelId',
    label: '模型id'
  },
  {
    field: 'modelName',
    label: '模型名称'
  },
  {
    field: 'jsonVersion',
    label: '版本'
  },
  {
    field: 'createBy',
    label: '创建人'
  },
  {
    field: 'createTime',
    label: '创建日期'
  },
  {
    field: 'updateBy',
    label: '更新人'
  },
  {
    field: 'updateTime',
    label: '更新时间'
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    width: 240,
    slots: {
      default: (data: any) => {
        const row = data.row
        return (
          <>
            <BaseButton type="primary" onClick={() => openTab(row)}>
              {t('exampleDemo.edit')}
            </BaseButton>
            <BaseButton type="success" onClick={() => showPreview(row)}>
              预览
            </BaseButton>
            <BaseButton type="danger" onClick={() => delData(row)}>
              {t('exampleDemo.del')}
            </BaseButton>
          </>
        )
      }
    }
  }
])

const delLoading = ref(false)
const delData = async (row) => {
  id.value = row.id || ''
  delLoading.value = true
  await delList(1).finally(() => {
    delLoading.value = false
  })
}
const searchSchema = reactive<FormSchema[]>([
  {
    field: 'formName',
    label: '表单名称',
    component: 'Input'
  }
])
const searchParams = ref({})
const setSearchParams = (data: any) => {
  searchParams.value = data
  getList()
}
const openTab = (row) => {
  push({
    path: '/lowCode/vform',
    query: { modelId: row.modelId, formName: row.formName, formId: row.id }
  })
}
const dialogVisible = ref(false)
const dialogTitle = ref('')
const showPreviewDialogFlag = ref(false)
const currentRow = ref()
const actionType = ref('')
const formJson = ref()
const writeRef = ref<ComponentRef<typeof Write>>()
const optionData = ref()
const saveLoading = ref(false)

const action = (row: any, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
  actionType.value = type
  currentRow.value = row
  dialogVisible.value = true
}
const showPreview = async (row) => {
  const res = await selectFormDetail({ formConfig: { id: row.id } })
  if (res.success) {
    formJson.value = res.result
    showPreviewDialogFlag.value = true
  }
}

const AddAction = () => {
  dialogTitle.value = t('exampleDemo.add')
  currentRow.value = undefined
  dialogVisible.value = true
  actionType.value = ''
}

const save = async () => {
  const write = unref(writeRef)
  const formData = actionType.value === 'edit' ? await write?.updateData() : await write?.submit()
  if (formData) {
    saveLoading.value = true
    // setTimeout(() => {
    //   saveLoading.value = false
    //   dialogVisible.value = false
    //   refresh()
    // }, 1000)
    push({
      path: '/lowCode/vform',
      query: { formName: formData.formName, modelId: formData.modelId }
    })
  }
}
</script>

<template>
  <ContentWrap>
    <Search
      :schema="searchSchema"
      @reset="setSearchParams"
      @search="setSearchParams"
      @register="searchRegister"
    />
    <div class="mb-10px">
      <BaseButton type="primary" @click="AddAction">{{ t('exampleDemo.add') }}</BaseButton>
    </div>
    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      @refresh="refresh"
      :columns="tableColumns"
      default-expand-all
      node-key="id"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total
      }"
      @register="tableRegister"
    />
  </ContentWrap>

  <Dialog v-model="dialogVisible" :title="dialogTitle" maxHeight="50px" maxWidth="30%">
    <Write v-if="actionType !== 'detail'" ref="writeRef" :current-row="currentRow" />
    <Detail v-else :current-row="currentRow" />

    <template #footer>
      <BaseButton
        v-if="actionType !== 'detail'"
        type="primary"
        :loading="saveLoading"
        @click="save"
      >
        创建
      </BaseButton>
      <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
    </template>
  </Dialog>
  <el-dialog
    title="预览"
    v-model="showPreviewDialogFlag"
    :show-close="true"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    draggable
    :destroy-on-close="true"
    :append-to-body="true"
    class="drag-dialog small-padding-dialog"
    width="50%"
  >
    <div>
      <div class="form-render-wrapper">
        <VFormRender
          ref="preForm"
          :form-json="formJson"
          :preview-state="true"
          :option-data="optionData"
        />
      </div>
    </div>
    <template #footer>
      <div>
        <el-button @click="showPreviewDialogFlag = false">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>
